<?php

// 设置数据库连接的初始值
header('content-type:text/html; charset=utf-8');
$servername = "localhost";
$username = "root";
$password = "020913";
$dbname = "part09"; // 数据库名称

// conn
// 获取数据库连接，命名为 mysqli 或者 conn
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
    die("连接失败: ".$conn->connect_error);
}
$conn->set_charset('utf8'); // 设置字符集

// 用户注册，插入新的数据到数据库
function register($conn)
{
    // mysqli_stmt
    // 插入数据库
    $sql = "INSERT INTO user(username, age, gender) VALUES(?, ?, ?)";
    $mysqli_stmt = $conn->prepare($sql); // 准备预处理语句

    // 代码写死：
    // $username = "小明";
    // $age = 18;
    // $gender = 1;
    // 获取页面上提交的数据
    $username = $_POST["username"];
    $age = $_POST["age"];
    $gender = $_POST["gender"];

    // s: string    i: int
    $mysqli_stmt->bind_param('sii', $username, $age, $gender);

    // 执行预处理的语句
    if($mysqli_stmt->execute()){
        // echo $mysqli_stmt->insert_id; // 程序执行成功，返回插入数据表的行 id
        echo PHP_EOL;
    }else{
        echo $mysqli_stmt->error; // 执行失败，展示错误信息
    }

    $mysqli_stmt->free_result();
    $mysqli_stmt->close();
}

// 读取用户并显示到页面
function getUserlist($conn)
{
    // 根据设置的主键 uid 查：
    // 预处理语句，后面的 ？，也是为了防止黑客的攻击
    $sql = "SELECT username, age, gender FROM user WHERE username = ? and password = ?";
    $mysqli_stmt = $conn->prepare($sql);

    // 获取页面提交的数据
    $username = $_GET["username"];
    $password = $_GET["password"];
    $mysqli_stmt->bind_param('ss', $username, $password);

    // 执行预处理语句
    if($mysqli_stmt->execute()){
        // bind_result() 绑定结果集中的值到变量
        $mysqli_stmt->bind_result($username, $age, $gender);
        // 遍历结果集
        while($mysqli_stmt->fetch()){
            echo "登陆成功，欢迎：" . $username . "<br>";
            echo "年龄：" . $age . "<br>";
            $gender = $gender == 1 ? '女' : '男';
            echo "性别：" . $gender . "<br>";

            echo "<br>";
        }
    }

    $mysqli_stmt->free_result();
    $mysqli_stmt->close();
}

// 读取用户并显示到页面
getUserlist($conn);

// 释放结果集
$conn->close(); 
